package com.sparsearray;

import java.io.*;

/**
 * @author 江岸
 * @version V1.0
 * @ClassName: SparseArray
 * @description: 二位数组转稀疏数组
 * @date 2020/9/1519:30
 * @since V1.0
 */
public class SparseArray {

    public static void main(String[] args) {
        //原始二维数组
        int[][] chessArr = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        for (int[] row:chessArr){
            for (int item:row){
                System.out.printf("%d\t",item);
            }
            System.out.println();
        }
        //转换成稀疏数组进行存储
        save(chessArr);
        //从磁盘读取稀疏数组复原
        read();
    }
    public  static void save(int[][] chessArr){
        int sum = 0;
        for (int[] row:chessArr){
            for (int item:row){
                if (item!=0){
                    sum++;
                }
            }
        }
        int[][] sparse = new int[sum+1][3];
        sparse[0][0] = 11;
        sparse[0][1] = 11;
        sparse[0][2] = sum;
        int count = 0;
        for (int i = 0;i<11;i++){
            for (int j = 0;j<11;j++){
                if (chessArr[i][j]!=0){
                    count++;
                    sparse[count][0] = i;
                    sparse[count][1] = j;
                    sparse[count][2] = chessArr[i][j];
                }
            }
        }
        //输出看看
        System.out.println("-----------------------------------------");
        for (int[] row:sparse){
            System.out.printf("%d\t%d\t%d\n",row[0],row[1],row[2]);
        }
        //存储在本地
        try(BufferedWriter bw =  new BufferedWriter(new FileWriter("d:\\sparse.txt"))){
            String mes = null;
            for (int[] row:sparse){
                mes = row[0]+","+row[1]+","+row[2];
                bw.write(mes);
                bw.newLine();
            }
        }catch (FileNotFoundException e){

        }catch (IOException e2){

        }
    }

    public static void  read(){
        //文件读取r
        try(BufferedReader br =  new BufferedReader(new FileReader("d:\\sparse.txt"))){
            String mes = br.readLine();
            String[] split = mes.split(",");
            int[][] ints = new int[Integer.parseInt(split[0])][Integer.parseInt(split[1])];
            while ((mes = br.readLine())!=null){
                String[] split1 = mes.split(",");
                ints[Integer.parseInt(split1[0])][Integer.parseInt(split1[1])] = Integer.parseInt(split1[2]);
            }
            System.out.println("-----------------------------------------");
            for (int[] row:ints){
                for (int item:row){
                    System.out.printf("%d\t",item);
                }
                System.out.println();
            }
        }catch (FileNotFoundException e){

        }catch (IOException e2){
        }

    }
}
